﻿using System;
using System.Linq;
using System.Linq.Expressions;
using System.Web.Mvc;

namespace HomeService.Helpers
{
    public static class HtmlHelpers
    {
        /// <summary>
        /// Extended version of the label helper that adds a class if the field is required.
        /// </summary>
        public static MvcHtmlString ImprovedLabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
        {
            var metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
            var htmlFieldName = ExpressionHelper.GetExpressionText(expression);
            var labelText = metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last();
            if (String.IsNullOrEmpty(labelText))
                return MvcHtmlString.Empty;

            var tag = new TagBuilder("label");
            tag.Attributes.Add("for", html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(htmlFieldName));
            tag.SetInnerText(labelText + ":");
            if (metadata.IsRequired)
                tag.AddCssClass("required");
            return MvcHtmlString.Create(tag.ToString());
        }

        /// <summary>
        /// Encodes the HTML in the string, and after that replaces newlines with line break elements.
        /// </summary>
        public static MvcHtmlString EncodeAndAddLineBreaks(this HtmlHelper html, string value)
        {
            var updatedValue = html.Encode(value).Replace(Environment.NewLine, "<br />");
            return MvcHtmlString.Create(updatedValue);
        }

        /// <summary>
        ///  Gets the display name for the property.
        /// </summary>
        public static MvcHtmlString DisplayNameFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
        {
            var metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
            var displayName = metadata.DisplayName ?? metadata.PropertyName;
            return MvcHtmlString.Create(displayName);
        }
    }
}